package cn.my.springHDFS.security;

import cn.my.springHDFS.service.ManagementServiceImpl;
import cn.my.springHDFS.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * Created by Leo on 2017/6/20.
 * 退出登录Handler
 */
@Component
public class LogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    ManagementServiceImpl managementService;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    UserServiceImpl userService;

    public LogoutSuccessHandler(){
        setDefaultTargetUrl("/");
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        super.onLogoutSuccess(request, response, authentication);
        String account = authentication.getPrincipal().toString();
        Object[] objectAuth = authentication.getAuthorities().toArray();
        if (!objectAuth[0].toString().equals("ROLE_USER")) {
            managementService.adminLoginInfo(managementService.findByAdminAccount(account), true, request);
        }
        else {
            userService.userLoginInfo(userService.findByuserAccount(account), true, request);
        }
    }
}
